package com.hyhy.hycloud.uaa.client;

import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

/**
 * 用户ID参数解析
 *
 * @author Xuegui Yuan
 * @date 2018-09-25
 */
@AllArgsConstructor
public class UserIdArgumentResolver implements HandlerMethodArgumentResolver {

    private UserInfoResourceService userInfoResourceService;

    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {
        return methodParameter.hasParameterAnnotation(CurrentUserId.class);
    }

    @Override
    public Object resolveArgument(MethodParameter methodParameter,
                                  ModelAndViewContainer modelAndViewContainer,
                                  NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) {
        CurrentUserId currentUserId = methodParameter.getParameterAnnotation(CurrentUserId.class);
        if (currentUserId == null) {
            return null;
        }
        String userId = nativeWebRequest.getHeader("X-User-Id");
        if (StringUtils.isBlank(userId)) {
            UserIdentity userIdentity = (UserIdentity) userInfoResourceService.loadUserInfo(
                    currentUserId.required(), false,
                    UserIdentity.class, nativeWebRequest);
            if (userIdentity != null) {
                return userIdentity.getId();
            }
        }
        return userId;
    }
}
